package com.spring.springsentinelclient.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Configuration
public class MyBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {

        AjaxResult ajaxResult = null;
        if(e instanceof FlowException){
            ajaxResult = AjaxResult.builder().status(100).msg("您的访问过于频繁，请稍后重试").build();
        }

        httpServletResponse.setStatus(500);

        httpServletResponse.setCharacterEncoding("utf-8");

        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);

//springmvc的一个json转换类(jockson)

        new ObjectMapper().writeValue(httpServletResponse.getWriter(),ajaxResult);

    }
}
